# -*- encoding: utf-8 -*-
#抓取大疆圆形禁飞区
import urllib,urllib2
import json
import codecs
import deCodeAirPort
from geojson_utils import draw_circle
import geojson
url='https://www.dji.com/cn/api/geo/areas'
ports=deCodeAirPort.getPortPos()
#去除字符中的中文乱码
def decodeCN(value):
     value=value.replace('u\'','\'')
     value=value.decode("unicode-escape") 
     return value
features=[]
geojson_obj=None
for port in ports:
    textmod ={'lng': port[0],
    'lat': port[1],
    'country': 'CN',
    'search_radius': 119931,
    'drone': 'spark',
    'level': '1,2,3',
    'zones_mode': 'total'}
    textmod = urllib.urlencode(textmod)
    print(textmod)
    #输出内容:password=admin&user=admin
    req = urllib2.Request(url = '%s%s%s' % (url,'?',textmod))
    res = urllib2.urlopen(req)
    res = res.read().decode("utf-8")
    geojson_data='{"crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:OGC:1.3:CRS84"}}, "type":"FeatureCollection","features":[]}'
    geojson_obj=json.loads(geojson_data)
    ori_json=json.loads(res)
    areas=ori_json['areas']
    file_name=""
    for area in areas:
        sub_areas=area['sub_areas']
        if len(sub_areas) == 0:
            lat=area['lat']
            lng=area['lng']
            pt=geojson.Point([float(lng),float(lat)])
            pt_data=geojson.dumps(pt)
            pt_center=json.loads(pt_data)
            radius=area['radius']
            if area['area_id'] == 33376:
                print(radius)
            circle_json=draw_circle(radius, pt_center)['coordinates']
            circle=geojson.Polygon(circle_json)
            geom=geojson.dumps(circle)
            geom_obj=json.loads(geom)
            feature_data='{"type":"Feature","geometry":{},"properties":{"name":""}}'
            feature_obj=json.loads(feature_data)
            feature_obj['geometry']=geom_obj
            feature_obj['properties']['name']=area['name']
            features.append(feature_obj)
geojson_obj['features']=features
geojson_data=json.dumps(geojson_obj)
filew = codecs.open("CircleLimit.geojson", "w", "utf-8")
geojson_data.replace('u\'','\'')
geojson_data=geojson_data.decode("unicode-escape") #将unicode编码转化为中文
filew.write(geojson_data+ "\n")
filew.close()
#输出内容:登录成功